<template>
  <div class="app-container">
    <div class="left_container1">
      <div class="mobile">
        <img src="../../../assets/image/wx2.png" alt="" />
        <span class="mobile_title">微信会员卡</span>
        <div
          class="Card"
          :style="{
            backgroundColor: !type ? settingForm.color : '',
            backgroundImage: type ? `url(${settingForm.new_background_pic_url})` : '',
            'background-size': 'cover',
          }"
        >
          <div class="user">
            <img class="userAvatar" :src="settingForm.logo_url" alt="" />
            <div>
              <div class="station">{{ settingForm.brand_name }}</div>
              <div style="font-size: 0.8rem">{{ settingForm.title }}</div>
            </div>
          </div>
          <div class="phone">{{ formattedPhone }}</div>
        </div>
        <div class="level">
          <div>
            <div>积分</div>
            <div :style="{ color: settingForm.color }">0</div>
          </div>
          <div>
            <div>{{ custom_field1.name }}</div>
            <div>
              <a
                :href="custom_field1.url"
                :style="{ color: settingForm.color, 'font-size': '0.8rem' }"
                >查看</a
              >
            </div>
          </div>
        </div>
        <div class="flue" v-show="settingForm.center_title">
          <el-button
            size="middle"
            :style="{
              color: settingForm.color,
              border: ` 1px solid ${settingForm.color}`,
            }"
            >{{ settingForm.center_title }}</el-button
          >
          <div
            class="sub_title1"
            style="color: #9f9a9a; font-size: 0.8rem; text-align: center"
          >
            {{ settingForm.center_sub_title }}
          </div>
        </div>
        <div class="detail">
          <div
            class="detail_btn"
            style="display: flex"
            v-show="settingForm.custom_url_name"
          >
            <span class="alt sub_title1">{{
              settingForm.custom_url_name
            }}</span>
            <span class="alt1 sub_title1" style="text-align: end">{{
              settingForm.custom_url_sub_title
            }}</span>
          </div>
          <div
            class="detail_btn"
            style="display: flex"
            v-show="settingForm.promotion_url_name"
          >
            <span class="alt sub_title1">{{
              settingForm.promotion_url_name
            }}</span>
            <span class="alt1 sub_title1" style="text-align: end">{{
              settingForm.promotion_url_sub_title
            }}</span>
          </div>
          <div class="detail_btn" style="display: flex">
            <span class="alt">会员卡详情</span>
          </div>
          <div class="detail_btn" style="display: flex">
            <span class="alt">公众号</span>
          </div>
        </div>
      </div>
    </div>
    <div class="right_container1">
      <el-form
        ref="settingForm"
        :model="settingForm"
        :rules="rules"
        label-width="110px"
      >
        <el-form-item label="商户名称" prop="brand_name">
          <el-input
            :disabled="true"
            placeholder=""
            size="small"
            v-model="settingForm.brand_name"
          ></el-input>
        </el-form-item>
        <el-form-item label="Logo" prop="logo_url">
          <el-upload
            class="avatar-uploader"
            :action="addressUrl"
            :headers="headers"
            :show-file-list="false"
            accept="image/png,image/jpg"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="settingForm.logo_url"
              :src="settingForm.logo_url"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">建议尺寸300x300</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="会员卡名称" prop="title">
          <el-input
            placeholder=""
            size="small"
            v-model="settingForm.title"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="卡面码型" prop="">
          <el-radio-group v-model="settingForm.number">
            <el-radio :label="3">仅展示卡号</el-radio>
            <el-radio :label="6">卡号+条形码</el-radio>
            <el-radio :label="9">卡号+二维码</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="封面类型" prop="">
          <el-radio-group v-model="type">
            <el-radio :label="false">颜色</el-radio>
            <el-radio :label="true">图片</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择背景颜色" prop="color" v-if="!type">
          <el-radio-group v-model="settingForm.color">
            <el-radio :label="v" v-for="v in colorList" :key="v">{{
              v
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="选择背景图片"
          prop="new_background_pic_url"
          v-if="type"
        >
          <el-upload
            class="avatar-uploader"
            :action="addressUrl"
            :headers="headers"
            :show-file-list="false"
            accept="image/png,image/jpg"
            :before-upload="beforeAvatarUpload1"
            :on-success="handleAvatarSuccess1"
          >
            <img
              v-if="settingForm.new_background_pic_url"
              :src="settingForm.new_background_pic_url"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <!-- <div class="el-upload__tip" slot="tip">建议尺寸300x300</div> -->
          </el-upload>
        </el-form-item>
        <div class="dashed"></div>
        <el-row>
          <el-col :span="2">
            <div style="margin-top: 3rem; font-size: 14px">中部入口</div>
          </el-col>
          <el-col :span="22">
            <el-form-item label="名称" prop="center_title">
              <el-input
                size="small"
                v-model="settingForm.center_title"
              ></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="center_sub_title">
              <el-input
                size="small"
                v-model="settingForm.center_sub_title"
              ></el-input>
            </el-form-item>
            <el-form-item label="链接" prop="center_url">
              <el-input
                size="small"
                v-model="settingForm.center_url"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="dashed"></div>
        <el-row>
          <el-col :span="2">
            <div style="margin-top: 3rem; font-size: 14px">自定义入口一</div>
          </el-col>
          <el-col :span="22">
            <el-form-item label="名称" prop="custom_url_name">
              <el-input
                size="small"
                v-model="settingForm.custom_url_name"
              ></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="custom_url_sub_title">
              <el-input
                size="small"
                v-model="settingForm.custom_url_sub_title"
              ></el-input>
            </el-form-item>
            <el-form-item label="链接" prop="custom_url">
              <el-input
                size="small"
                v-model="settingForm.custom_url"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="dashed"></div>
        <el-row>
          <el-col :span="2">
            <div style="margin-top: 3rem; font-size: 14px">自定义入口二</div>
          </el-col>
          <el-col :span="22">
            <el-form-item label="名称" prop="promotion_url_name">
              <el-input
                size="small"
                v-model="settingForm.promotion_url_name"
              ></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="promotion_url_sub_title">
              <el-input
                size="small"
                v-model="settingForm.promotion_url_sub_title"
              ></el-input>
            </el-form-item>
            <el-form-item label="链接" prop="promotion_url">
              <el-input
                size="small"
                v-model="settingForm.promotion_url"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="Footer">
        <el-button type="primary" @click="update" :loading="loading">保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { getMemberCard, updateCard, uploadWxImgDto, bgPicUpload } from "@/api/MenuSetting/index";
import { cloneDeep } from "lodash";
export default {
  name: "memberShip",
  data() {
    var validateTitle = (rule, value, callback) => {
      if (value) {
        const chineseCharCount = (value.match(/[\u4e00-\u9fa5]/g) || []).length; // 统计汉字个数
        const otherCharCount = value.length - chineseCharCount; // 统计非汉字个数
        if (chineseCharCount * 2 + otherCharCount > rule.max) {
          callback(new Error(`最多${rule.max}个字符`));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    var validateUrl = (rule, value, callback) => {
      if (value && !/^https?:\/\//i.test(value)) {
        callback(new Error("链接必须以http://或https://开头"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      custom_field1: "", // 积分配置
      background_pic_url: "", // 背景图片
      phone: 123456789000,
      settingForm: {}, // 表单数据
      data: {}, // 数据原件
      rules: {
        new_background_pic_url: [
          { required: true, message: "请上传背景图片", trigger: "change" },
        ],
        color: [
          { required: true, message: "请选中背景颜色", trigger: "change" },
        ],
        title: [
          { required: true, message: "请输入会员卡名称", trigger: "blur" },
          {
            pattern: /^(?:[\u4e00-\u9fa5\w]){1,9}$/,
            message: "字数上限9个汉字",
            trigger: "blur",
          },
        ],
        logo_url: [
          { required: true, message: "请上传Logo", trigger: "change" },
        ],
        brand_name: [
          { required: true, message: "请输入商户名称", trigger: "blur" },
        ],
        custom_url: [
        { validator: validateUrl, trigger: "blur" },
        { validator: validateTitle, trigger: "blur", max: 128 },
        ],
        custom_url_sub_title: [
        { validator: validateTitle, trigger: "blur", max: 18 },
        ],
        custom_url_name: [
        { validator: validateTitle, trigger: "blur", max: 16 },
        ],
        promotion_url: [
        { validator: validateUrl, trigger: "blur" },
        { validator: validateTitle, trigger: "blur", max: 128 },
        ],
        promotion_url_sub_title: [
        { validator: validateTitle, trigger: "blur", max: 18 },
        ],
        promotion_url_name: [
        { validator: validateTitle, trigger: "blur", max: 16 },
        ],
        center_url: [
        { validator: validateTitle, trigger: "blur", max: 128 },
        { validator: validateUrl, trigger: "blur" },
        ],
        center_sub_title: [
        { validator: validateTitle, trigger: "blur", max: 24 },
        ],
        center_title: [
        { validator: validateTitle, trigger: "blur", max: 18 },
        ],
      }, //表单校验
      colorList: [
        "#63b359",
        "#2c9f67",
        "#509fc9",
        "#5885cf",
        "#9062c0",
        "#d09a45",
        "#e4b138",
        "#ee903c",
        "#f08500",
        "#a9d92d",
        "#dd6549",
        "#cc463d",
        "#cf3e36",
        "#5e6671",
      ],
      addressUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      type: false,
    };
  },
  computed: {
    formattedPhone() {
      return this.phone.toString().replace(/\B(?=(\d{4})+(?!\d))/g, " ");
    },
  },
  watch: {
    //用来选中颜色 还是背景
    background_pic_url(newVal) {
      if (newVal && newVal != 0) {
        this.type = true;
      }
    },
  },
  created() {
    this.getCardInfo();
  },
  methods: {
    // 保存背景图片
    async uploadBJ(url) {
      await bgPicUpload(url)
    },
    // 保存提交
    async update() {
      await this.$refs["settingForm"].validate();
      this.loading = true
      let obj = { member_card: {} };
      if (this.settingForm.new_background_pic_url ) {
        const res = await this.updateImg(this.settingForm.new_background_pic_url)
        await this.uploadBJ(this.settingForm.new_background_pic_url )
        this.settingForm.new_background_pic_url = res && JSON.parse(res).url
        obj.member_card.background_pic_url =
          this.settingForm.new_background_pic_url;
        delete this.settingForm["new_background_pic_url"];
      }
      if(!this.type) {
        await this.uploadBJ(0)
        delete obj.member_card.background_pic_url
      }
      obj.member_card.base_info = this.settingForm;
      if(this.type) {
        delete obj.member_card.base_info.color
      }
      obj = JSON.stringify(obj);
      try{
        const res = await updateCard(obj);
        setTimeout(() => {
          this.getCardInfo();
          this.$message.success("保存成功");
        }, 1200);
      }finally {
        this.loading = false
      }
    },
    // 获取会员卡数据
    async getCardInfo() {
      this.settingForm = {
        color: "transparent",
      };
      const res = await getMemberCard();
      let cardData = res.data.response.card.member_card
      if (res.code != "200") return;
      cardData.base_info.color = cardData.base_info.color.toLowerCase();
      this.custom_field1 = cardData.custom_field1;
      this.settingForm = cloneDeep(cardData.base_info);
      if(res.data.backgroundPicUrl && res.data.backgroundPicUrl != 0) {
        this.background_pic_url = res.data.backgroundPicUrl;
        this.$set(this.settingForm, 'new_background_pic_url', this.background_pic_url)
      }
      this.data = cloneDeep(cardData);
    },
    // 上传图片
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    handleAvatarSuccess(response, file) {
      console.log(response);
      this.settingForm = {
        ...this.settingForm,
        logo_url: response.url,
      };
    },
    // 上传图片
    beforeAvatarUpload1(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      // const isJPG = file.type == "image/jpg";
      const isPNG = file.type == "image/png";
      // const isJPEG = file.type == "image/jpeg";
      console.log(file.type);
      if (!isLt2M) {
        this.$message.error("上传背景图片大小不能超过 2MB!");
      } else if (!isPNG ) {
        this.$message.error("上传背景图片只能是 PNG 格式!");
      }
      return isPNG && isLt2M;
    },
    handleAvatarSuccess1(response, file) {
      console.log(response);
      this.settingForm = {
        ...this.settingForm,
        new_background_pic_url: response.url,
      };
    },
     // 上传微信图片
     async updateImg(url) {
      const res = await uploadWxImgDto(url);
      return res.data;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__error {
  margin-top: -1rem;
}
.app-container {
  padding-top: 38px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-evenly;

  .left_container1 {
    width: 21rem;
    height: 40rem;
    border: 1px solid #ededed;
    padding: 0.5rem;
    box-sizing: border-box;
    box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
    .mobile {
      position: relative;
      width: 100%;
      box-sizing: border-box;
      height: 100%;
      .mobile_title {
        display: inline-block;
        position: absolute;
        font-size: 0.8rem;
        font-weight: 500;
        left: 50%;
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
        top: 1.3rem;
      }
      img {
        vertical-align: middle;
        border-style: none;
        // width: 100%;
      }
    }
  }
  .right_container1 {
    display: flex;
    flex-direction: column;
    padding-left: 5rem;
    box-sizing: border-box;
    flex: 1;
    position: relative;
    font-size: 12px;
    .Footer {
      margin: 0 auto;
    }
    .dashed {
      border-top: 1px dashed #a9a9a9; /* 设置顶部边框为虚线 */
      width: 100%; /* 设置宽度，根据需要进行调整 */
      margin: 8px 0;
    }
    .avatar-uploader {
      .el-upload {
        border: 2px dashed #8c939d;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        background-color: #fff;
      }

      .el-upload__tip {
        margin-top: -1rem;
      }
      .el-upload:hover {
        border-color: #409eff;
      }

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 6rem;
        height: 6rem;
        line-height: 6rem;
        text-align: center;
      }

      .avatar {
        width: 6rem;
        height: 6rem;
        display: block;
      }
    }
    .avatar-uploader {
      margin-left: 0;
      .avatar-uploader-icon {
        width: 6rem;
        height: 3rem;
        line-height: 3rem;
      }
      .el-upload {
        width: 6rem;
        height: 3rem;
        border: 2px dashed #8c939d;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        background-color: #fff;
      }
      .el-upload__tip {
        margin-top: -1.5rem;
      }
      .avatar {
        width: 6rem;
        height: 3rem;
        background-size: 100% 100%;
      }
    }
    .el-form-item {
      margin-bottom: 0;
    }
    .el-input {
      width: 80%;
    }
    .el-radio-group {
      vertical-align: text-top;
      width: 80%;
    }
    .el-form-item__content {
      margin-left: 0;
    }
  }
}
.Card {
  margin: 2rem 1rem 0.5rem 1rem;
  width: 18rem;
  height: 10rem;
  background-color: #63b359;
  border-radius: 0.5rem;
  display: flex;
  padding: 1rem;
  box-sizing: border-box;
  flex-direction: column;
  color: #fff;
  .user {
    display: flex;
    .userAvatar {
      width: 2.8rem;
      height: 2.8rem;
      border-radius: 2.8rem;
      margin-right: 0.5rem;
      margin-bottom: 3.5rem;
    }
    .station {
      width: 13rem;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
}
.level {
  display: flex;
  align-items: center;
  text-align: center;
  justify-content: space-between;
  padding: 0 4rem 2rem 4rem;
  box-sizing: border-box;
}
.flue {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 1.5rem;

  .el-button {
    margin-bottom: 0.5rem;
    width: 10rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.detail {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  .detail_btn {
    width: 100%;
    height: 3rem;
    line-height: 3rem;
    border-bottom: 1px solid #dedcdc;
    display: flex;
    justify-content: flex-end;
    .alt {
      font-size: 0.8rem;
      font-weight: 600;
      margin-right: auto;
    }
    .alt1 {
      font-size: 0.8rem;
      font-weight: 500;
      color: #848080;
      text-align: center;
    }
  }
}
.sub_title1 {
  text-align: start;
  width: 10rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
::v-deep .el-upload {
  width: 6rem;
  height: 3rem;
  border: 2px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fff;
}
</style>
